<template>
  <div style="position: relative;" class="routeListC">
    <div>
      <head-nav :firstTitle="'影像存档'" :subTitle="'路由列表'"></head-nav>
    </div>
    <div ref="tabHeight" class="ml20">
      <!--      <head-tab-switch navTitle="影像列表"/>-->
    </div>
    <div ref="condationHeight" class="ml10 mt5 mb">
      <condition-inquery :routing_state="formData.routing_state" :systemsLiteList="systemsLiteList"
        :room_ids="ObservationRoomIds" @setRouteState="setRouteState" @search="searchFn"
        @recalculateTableHeight="recalculateTableHeight" />
    </div>

    <div class="btnBox fr mb5 mt5 mr20">
      <el-button v-if="hasPerimission('yxcf')" @click="refreshFn" type="primary" plain>刷新</el-button>
      <el-button v-if="hasPerimission('yxpp')" @click="reRouteFn" type="primary" plain class="ml10i">重新路由</el-button>
      <el-button v-if="hasPerimission('yxsc')" @click="deleteFn" type="danger" plain class="ml10i">删除</el-button>
    </div>

    <el-table :data="tableData" border ref="mytable" :header-cell-style="{ background: '#F5F5F5', color: '#333' }"
      height="calc(100vh - 300px)" highlight-current-row @row-click="handleCurrentChange" @select="tableSignleSelection"
      @selection-change="tableSelectionChange" @header-dragend="tableHeaderDragend" :row-key="getRowKey" @select-all="tableAllSelection"
      header-row-class-name="strong">

      <el-table-column fixed="left" type="selection" :reserve-selection="true"></el-table-column>
      <el-table-column label="序" width="55" fixed="left" align="center">
        <template slot-scope="scope">
          {{ orderNum + 1 + scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="130" fixed="left" align="center">
        <template slot-scope="scope">
          <el-button @click="singleReRouteFn(scope.row)" type="text" size="small"
            :disabled="scope.row.routing_state === 0">重新路由</el-button>
          <el-button @click="singleDeleteFn(scope.row)" type="text" size="small" class="btn_style">删除</el-button>

        </template>
      </el-table-column>
      <el-table-column label="路由状态" width="100" prop="routing_state" align="center" fixed="left">
        <template slot-scope="scope">
          <div v-if="scope.row.routing_state === 0">
            <i class="inline w10 h10 bg9 bradius5 mr6"></i>
            <span>未路由</span>
          </div>
          <div v-if="scope.row.routing_state === -1 || scope.row.routing_state === -2 || scope.row.routing_state === -3">
            <i class="inline w10 h10 bg_ff6f6f bradius5 mr6"></i>
            <span>失败</span>
          </div>
          <div v-if="scope.row.routing_state === 1">
            <i class="inline w10 h10 bg_49b523 bradius5 mr6"></i>
            <span>成功</span>
          </div>

        </template>
      </el-table-column>

      <common-table :propData="propData"></common-table>
      <!-- <el-table-column fixed="right" align="right" width="50">
        <template slot="header">
          <span class="el-icon-s-tools" @click="SetColumndShow = true"></span>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- 分页 -->
    <div ref="paginationHeight">
      <pagination-tool :total="total" :page.sync="listQuery.page_index" :limit.sync="listQuery.page_size"
        @pagination="fecthTableData" />
    </div>

    <!-- 删除路由 -->
    <el-dialog v-if="delDailog" title="删除" :visible.sync="delDailog" width="380px" top="31vh" :before-close="handleClose">
      <div class="pt20 pl20 pb20 bbd">
        <div class="clr_warn mb10">
          <i class="iconfont clr_warn" style="font-size: 20px;">&#xe680;</i>
          <span class="f16 ml5">
            确认删除
          </span>
        </div>
        <div class="pb10">确认要删除{{ dialogNumStr }}路由任务吗？</div>

      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取消</el-button>
        <el-button size="small" type="primary" @click="handleSure">确定</el-button>
      </span>
    </el-dialog>
    <!-- 重新路由 -->
    <el-dialog v-if="reRouteDailog" title="重新路由" :visible.sync="reRouteDailog" width="380px" top="31vh"
      :before-close="handleReRouteClose" >
      <div class="pt20 pl20 pb20 bbd">
        <div class="clr_warn mb10">
          <i class="iconfont clr_warn" style="font-size: 20px;">&#xe680;</i>
          <span class="f16 ml5">
            确认重新路由
          </span>
        </div>
        <div class="pb10">确认要重新路由所选的{{ dialogNumStr }}任务吗？</div>

      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleReRouteClose">取消</el-button>
        <el-button size="small" type="primary" @click="handleReRouteSure">确定</el-button>
      </span>
    </el-dialog>
  
  </div>
</template>
<script>
import Vue from 'vue'
import JSEncrypt from 'jsencrypt'
import HeadNav from "@/components/common/HeadNav"; // 头部导航
import HeadTabSwitch from '@/components/common/HeadTabSwitch' // 头部tab
import ConditionInquery from './components/ConditionInquery' // 查询条件
import CommonTable from '@/components/common/CommonTable' // 表格
import PaginationTool from '@/components/common/PaginationTool' // 分页
import { recalculateTableHeight } from '@/utils/mixin/filter' // 计算table 高度
import moment from 'moment'
import { mapGetters } from 'vuex'
import Mgr from '@/utils/SecurityService'
import store from '@/store/index'
import { getConfigurations } from '@/api/Public.js'

export default {
  name: 'RouteList',
  data() {
    return {
      BacsUrl: configUrl.frontEndUrl, // configUrl.frontEndUrl,,
      owner: 'archiveManage-studyList',
      SetColumndShow: false,
      TranspondImgShow: false,
      // TranspondData:'',
      tableHeight: 0,
      currentTableChecked: [], // 表格当中选中的行
      propData: [
        {
          prop: 'other_patient_name',
          label: '患者姓名',
          width: 120,
          formatter: function (row) {
            let name = '';
            name = row.other_patient_name ? row.other_patient_name : row.patient_name;
            return name;
          }
        },
        {
          prop: 'patient_id',
          label: '患者编号',
          width: 160
        },
        {
          prop: 'patient_sex',
          label: '性别',
          width: 50,
          formatter: function (row) {
            const sexMapping = {
              M: '男',
              F: '女',
              O: '未知'
            }
            return sexMapping[row.patient_sex]
          }
        },
        {
          prop: 'patient_age',
          label: '年龄',
          width: 60,
          formatter: function (row) {
            const patient_ageTypeMapping = {
              'Y': '岁',
              'M': '月',
              'D': '日',
              'W': '周'
            }
            let patient_ageNum = ''
            let patient_ageType = ''
            if (row.patient_age) {
              patient_ageNum = row.patient_age.substring(0, row.patient_age.length - 1)
              patient_ageType = row.patient_age.substring(row.patient_age.length - 1, row.patient_age.length)
              return patient_ageNum + patient_ageTypeMapping[patient_ageType]
            } else {
              return ''
            }
          }
        },
        {
          prop: 'modalities_in_study',
          label: '检查类型',
          width: 80
        },
        {
          prop: 'accession_number',
          label: '检查编号',
          width: 100
        },
        {
          prop: 'study_date_time',
          label: '检查时间',
          width: 160,
          formatter: function (row) {
            if (row.study_date_time) {
              return moment(row.study_date_time).format('YYYY-MM-DD HH:mm:ss')
            } else {
              return ''
            }
          }
        },
        {
          prop: 'system_name',
          label: '系统名称',
          width: 150
        },
        {
          prop: 'institution_name',
          label: '机构名称',
          width: 150
        },
        {
          prop: 'dest_ae_title',
          label: '目标节点标识',
          width: 120
        },
        {
          prop: 'priority',
          label: '优先级',
          width: 80,
          formatter: function (row) {
            if (row.priority === 0) {
              return '普通'
            } else if (row.priority === 1) {
              return '优先'
            } else {
              return ''
            }
          }
        },
        {
          prop: 'create_time',
          label: '任务创建时间',
          width: 160
        },
        {
          prop: 'routing_time',
          label: '路由时间',
          width: 100
        },
        {
          prop: 'error_desc',
          label: '失败原因',
          width: 100
        }
      ], // table表格原始表头数据
      tableData: [],
      defaultColumn: [
        //   { owner: 'archiveManage-studyList', field_code: 'id', field_name: '检查主键', column_width: 100, essential: 1, visibility: 1, fixed: 0, sort: 1 },
        //   { owner: 'archiveManage-studyList', field_code: 'patient_name', field_name: '患者姓名', column_width: 120, essential: 1, visibility: 1, fixed: 0, sort: 2 },
        //   { owner: 'archiveManage-studyList', field_code: 'patient_id', field_name: '患者编号', column_width: 160, essential: 1, visibility: 1, fixed: 0, sort: 3 },
        //   { owner: 'archiveManage-studyList', field_code: 'patient_sex', field_name: '性别', column_width: 50, essential: 1, visibility: 1, fixed: 0, sort: 4 },
        //   { owner: 'archiveManage-studyList', field_code: 'patient_age', field_name: '年龄', column_width: 60, essential: 1, visibility: 1, fixed: 0, sort: 5 },
        //   { owner: 'archiveManage-studyList', field_code: 'patient_birth_date', field_name: '出生日期', column_width: 160, essential: 1, visibility: 1, fixed: 0, sort: 6 },
        //   { owner: 'archiveManage-studyList', field_code: 'modalities_in_study', field_name: '检查类型', column_width: 80, essential: 1, visibility: 1, fixed: 0, sort: 7 },
        //   { owner: 'archiveManage-studyList', field_code: 'accession_number', field_name: '检查编号', column_width: 100, essential: 1, visibility: 1, fixed: 0, sort: 8 },
        //   { owner: 'archiveManage-studyList', field_code: 'study_date_time', field_name: '检查时间', column_width: 160, essential: 1, visibility: 1, fixed: 0, sort: 9 },
        //   { owner: 'archiveManage-studyList', field_code: 'study_description', field_name: '检查描述', column_width: 100, essential: 1, visibility: 1, fixed: 0, sort: 10 },
        //   { owner: 'archiveManage-studyList', field_code: 'source_aet', field_name: '来源设备', column_width: 120, essential: 1, visibility: 1, fixed: 0, sort: 11 },
        //   { owner: 'archiveManage-studyList', field_code: 'observation_room_name', field_name: '来源机房', column_width: 120, essential: 1, visibility: 1, fixed: 0, sort: 12 },
        //   { owner: 'archiveManage-studyList', field_code: 'storage_state', field_name: '访问状态', column_width: 80, essential: 1, visibility: 1, fixed: 0, sort: 13 },
        //   { owner: 'archiveManage-studyList', field_code: 'volume_label', field_name: '备份标卷', column_width: 100, essential: 1, visibility: 1, fixed: 0, sort: 14 },
        //   { owner: 'archiveManage-studyList', field_code: 'system_name', field_name: '系统名称', column_width: 100, essential: 1, visibility: 1, fixed: 0, sort: 15 },
        //   { owner: 'archiveManage-studyList', field_code: 'institution_name', field_name: '机构名称', column_width: 100, essential: 1, visibility: 1, fixed: 0, sort: 16 }
      ],
      listQuery: {
        page_index: 1,
        page_size: 20
      },
      formData: { routing_state: '' },
      total: 10000,
      rowId: 0,
      dialogType: '', // 弹窗的类型: 查看view 修改modify
      currentRow: null, // 表格当前点击的行
      baseUrl: '',
      SystemId: '',
      InstitutionId: '',
      pathUrl: '',
      systemsLiteList: [], // 系统名称
      delDailog: false,
      reRouteDailog:false,
      dialogDatas: [],
      dialogNumStr: '该条',
      delPass: '',
      delId: '',
      delObj: {},
      profile: {
        name: ''
      },
      delSeqObj: {},
      currentSystemClass: '',
      ObservationRoomIds: []
    }
  },
  mixins: [recalculateTableHeight],
  mounted() {

    this.currentSystemClass = sessionStorage.getItem('currentSystemClass') || ''
    this.profile = JSON.parse(this.loginInfo)?.profile
    this.pathUrl = process.env.NODE_ENV === 'development' ? '' : '/paservice'
    this.baseUrl = process.env.NODE_ENV === 'development' ? 'http://www.eworlds.com.cn' : configUrl.frontEndUrl
    // if (this.$route.query.institution_id) {
    //   store.commit('permission/SET_DEPTINSTITUTIONID', this.$route.query.institution_id)
    // }

    // if (this.$route.query.ObservationRoomIds) {
    //   this.ObservationRoomIds = JSON.parse(this.$route.query.ObservationRoomIds)
    // }


    // if (this.$route.query?.showMatchFailed) {
    //   this.formData.routing_state = -1
    // }
    if (this.scope && this.scope === 'institution' && this.systemid) {
      // 本地取得institution
      // this.getUserInfo()
      this.SystemId = this.systemid
      this.InstitutionId = this.deptInstitutionId
    } else if (this.scope && this.scope === 'system' && this.systemid) {
      this.SystemId = this.systemid
    }



    // this.currentRightCheckedData = this.propData // 复制一份
    //   if (this.currentSystemClass === 'NMIS') {
    //     this.propData = [...this.defaultColumn]
    //   } else {
    //     this.getColumnCustom()
    //   }
    this.getSystemsLiteList() // 获取系统名称
    this.getConfigurationsFn()
  },
  computed: {
    orderNum() {
      if (this.listQuery.page_index === 1) {
        return 0
      } else {
        return (this.listQuery.page_index - 1) * this.listQuery.page_size
      }
    },
    ...mapGetters(['group', 'permissions', 'permissionsMapping', 'systemid', 'scope', 'deptInstitutionId','loginInfo'])
  },
  watch: {
    // $route: {
    //   handler: function (newVal) {
    //     console.log(newVal)
    //     if(newVal.query['routing_state'] && newVal.query['routing_state'] === '0') {
    //       this.formData.routing_state = 0
    //     }else {
    //       this.formData.routing_state = ''
    //     }
    //     if(newVal.path === '/IMGLIST') {
    //       this.getIMGList()
    //     }
    //   },
    //   deep: true,
    //   immediate: true
    // },

  },
  methods: {
    getRowKey(row) {
      return row.id
    },
    // 是否有权限
    hasPerimission(permissionName) {
      if (this.group === 'tenancy') {
        return true
      }
      return this.permissions.includes(permissionName)
    },
    
   
    //单条路由
    singleReRouteFn(rowData) {
      this.dialogDatas  = [rowData.id]
      this.reRoute(this.dialogDatas);
    },
    //批量路由
    reRouteFn() {
      if (this.currentTableChecked.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择需要重新路由的任务',
          type: 'warning'
        })
        return
      }
      this.dialogDatas = this.currentTableChecked.map(e => e.id);
      this.dialogNumStr = this.dialogDatas.length == 1 ? '该条' : (this.dialogDatas.length + '条')
      this.reRouteDailog = true;
    },

    handleReRouteClose() {
      this.reRouteDailog = false
      this.dialogDatas = []

    },
    handleReRouteSure() {
      this.reRouteDailog = false
      this.reRoute(this.dialogDatas);
      this.clearSelection()

    },

    async reRoute(ids) {
      let [res, err] = await this.$pacsApi.pacsApi.reRoute(ids)
      this.dialogDatas = []
      if (!err) {
        let { code, msg } = res
        if (code === 0) {
          this.$message({
            type: 'success',
            message: '已重置路由状态并加入路由队列，请等待执行',
          })
          this.getRouteList();
          this.currentTableChecked = []
        } else {
          this.$message.error(res.msg)
        }
      }
    },
    singleDeleteFn(rowData) {

      this.dialogDatas = [rowData.id]
      this.dialogNumStr = '该条'
      this.delDailog = true
    },
    deleteFn() {
      if (this.currentTableChecked.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择要删除的内容',
          type: 'warning'
        })
        return
      }
      this.dialogDatas = this.currentTableChecked.map(e => e.id);

      this.dialogNumStr = this.dialogDatas.length == 1 ? '该条' : (this.dialogDatas.length + '条')
      this.delDailog = true
      // if (this.currentTableChecked.length === 1) {
      //   this.$confirm('确定要删除该条路由任务吗？', '确认删除', {
      //     confirmButtonText: '确认',
      //     cancelButtonText: '取消',
      //     type: 'warning',
      //     center: true,
      //   }).then((action) => {
      //     let ids = this.currentTableChecked.map(e => e.id);

      //     this.deleteRoute(ids);
      //   }).catch((action) => {
      //     // console.log("取消删除了哦");
      //   });
      // } else {
      //   this.$confirm(`确定要删除${this.currentTableChecked.length}条路由任务吗？`, '提示', {
      //     confirmButtonText: '确认',
      //     cancelButtonText: '取消',
      //     type: 'warning',
      //     center: true,
      //   }).then((action) => {
      //     let ids = this.currentTableChecked.map(e => e.id);

      //     this.deleteRoute(ids);
      //   }).catch((action) => {
      //     // console.log("取消删除了哦");
      //   });
      // }
    },

    async deleteRoute(ids) {
      let [res, err] = await this.$pacsApi.pacsApi.deleteRoute(ids)
      this.dialogDatas = []
      if (!err) {
        let { code, msg } = res
        if (code === 0) {
          this.$message({
            type: 'success',
            message: msg
          })
          this.getRouteList();
        } else {
          this.$message.error(res.msg)
        }
      }
    },



    async handleSure() {
      this.delDailog = false
      this.deleteRoute(this.dialogDatas);
      this.clearSelection()


    },
    handleClose() {
      
      this.delDailog = false
      this.dialogDatas = []
    },
    async getConfigurationsFn() {
      const res = await getConfigurations('TransmissionSecurity.RSA.PublicKey')
      if (res.code === 0) {
        // rsa加密
        Vue.prototype.$getRsaCode = function (str) { // 注册方法
          const pubKey = res.data// ES6 模板字符串 引用 rsa 公钥
          const encryptStr = new JSEncrypt()
          encryptStr.setPublicKey(pubKey) // 设置 加密公钥
          const data = encryptStr.encrypt(str.toString()) // 进行加密
          return data
        }
      }
    },


    async getRouteList(closeLoading) { // 获取列表
      const data = Object.assign(this.formData, this.listQuery)
      data.system_id = this.SystemId ? this.SystemId : this.formData.system_id
      data.institution_id = this.InstitutionId ? this.InstitutionId : this.formData.institution_id
      if (data.routing_state === 100) {
        data.routing_state = null
      }
      let [res, err] = await this.$pacsApi.pacsApi.getRouteList(data);
      if (closeLoading) {
        this.loading.close();
      }
      if (!err) {

        if (res.code === 0) {
          this.tableData = res.data
          this.total = res.page.total_count
          this.$refs.mytable.doLayout()
        }
      }



    },
    async fecthTableData() { // 翻页改变
      this.tableData = []
      this.getRouteList()
    },
    searchFn(params) { // 搜素

    this.clearSelection()
      // console.log('默认搜索参数list',params);
      this.listQuery.page_index = 1 // 重置页数
      this.formData = params
      this.getRouteList()
    },
    setRouteState(val) {
      this.formData.routing_state = val
    },
    // 表格操作
    handleCurrentChange(val) {
      this.currentRow = val
      
    },
    tableSignleSelection(rows, row) {
      this.currentTableChecked = rows
    },
    tableAllSelection(rows){
      this.currentTableChecked = rows

    },
    tableSelectionChange(rows) {
      if (rows.length === 0 && this.currentTableChecked.length !== 0) {
        this.currentTableChecked = []
      }
    },
    tableHeaderDragend() {
      this.$refs.mytable.doLayout()
    },

    async getSystemsLiteList() {
      let res = await this.$pacsApi.pacsApi.getSystemsLiteList({ type: 1 })
      let { code, data } = res
      if (code === 0) {
        this.systemsLiteList = data
      }
    },
    // 刷新列表
    refreshFn() {
      this.loading = this.$loading({
        lock: true,
        text: '刷新中...',
        spinner: 'el-icon-loading',
      });
      this.getRouteList(true);

    },
    clearSelection() {
      this.currentTableChecked = []
      this.$nextTick(() => {
        this.$refs.mytable.clearSelection()
      })
    },
  },
  components: {
    HeadNav,
    HeadTabSwitch,
    ConditionInquery,
    CommonTable,
    PaginationTool,
  }
}
</script>
<style lang="less" scoped>
.routeListC {
  /deep/ .el-dialog__body {
    padding: 0px;
  }
}

/deep/ .listRoomClass .el-select__tags-text {
  display: inline-block;
  max-width: 78px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/deep/ .listRoomClass .el-icon-close {
  margin-top: -13px;
  margin-left: -6px;
}

.w180 {
  width: 180px;
}

.bg_000 {
  background-color: #000000;
}

.btnBox {

  // position: absolute;
  // right: 20px;
  // top: 95px;
  // margin-bottom: 20px;
  button {
    width: 70px;
    height: 32px;
    background-color: #fff;
    border: 1px solid #DCDFE6;
    padding: 0;
  }
}

.f18i {
  font-size: 18px !important;
}

.f20i {
  font-size: 20px !important;
}

.el-button+.el-button {
  margin-left: 5px;
}

.btn_style {
  color: #FF6F6F;
}


.btn_style:focus,
.btn_style:hover {
  color: #f99999;
}

.btn_style:active {
  color: #f99999;
}



.ml10i {
  margin-left: 10px !important;
}

//   /deep/ .el-table__body tr.current-row>td {
//   // 色值待确定
//   background-color: #0a70b0;
//   color: white;
// }
// /deep/.el-table__fixed .el-table__fixed-body-wrapper{
//   top: 42px !important;
//   // height: 100% !important;  //会有bug  左边序号超过15显示不全 
// }
// /deep/.el-table__row .cell {
//   width: 100% !important;
// }
// /deep/ .el-table .el-table__fixed {
//   height: 100% !important;
// }
// /deep/ .el-table__fixed-body-wrapper .el-table__body{
//   padding-bottom: 8px;//滚动条的高度
// }
.img_box {
  overflow-x: auto;
  display: flex;

  div {
    height: 200px;
    margin-right: 15px;
    // margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
}

.imgLoadFail {
  width: 94px;
  height: 90px;
  background: url("../../assets/images/pacs/imgLoadFail.png") no-repeat;
  background-size: 100% 100%;
}

.noImg {
  width: 58px;
  height: 90px;
  background: url("../../assets/images/pacs/noImg.png") no-repeat;
  background-size: 100% 100%;
}

.del_btn {
  position: absolute;
  top: 0px;
  right: -12px;
  cursor: pointer;
  z-index: 10;
}
</style>
  